﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HR60_PanelSoft.Model;

namespace HR60_PanelSoft.Service 
{
    //GC: [g1]执行业务约束[NetService]@s1

    //GC: [g2]面板删除逻辑增加智能终端逻辑[NetService]


	public class NetService : CommonService
	{
        /* [g1.s1] */
        /*
         * 初始化约束因子 
         */
        protected static int MaxNetsInProc = 8;


        public static bool IsCanNew(HR60_PanelSoft.Model.BaseModel.RefModel ins)
        {
            bool rst = false;

            if (proj.nets.Count < MaxNetsInProc)
                rst = true;
            return rst;
        }
        
        /* end of [g1.s1] */
		// 保存
		public static void save(HR60_PanelSoft.Model.Net source, HR60_PanelSoft.Model.Net dto)
		{
			source.name = dto.name;
			source.index = dto.index;
		}
		
		// 添加
		public static void append(HR60_PanelSoft.Model.Net net)
		{
            /* [g1.s2] 追加新的网络 */
            if (!IsCanNew(net))
            {
                View.ViewUtils.showAlert("一个工程中最多设置" + MaxNetsInProc.ToString() + "个网络！" +
                    " 当前网络数为" + proj.nets.Count.ToString() + "个。\r\n");
                RestrictErr = true; /* 设置约束错误标记 */
                return;
            }
            else
                RestrictErr = false;
            /* end of [g1.s2] */
			proj.nets.Add (net);
		}

		// 删除
		public static void remove(HR60_PanelSoft.Model.Net net)
		{
			// 删除下辖的面板

            /* [g2.s1]优化删除，防止有删除失败情况 */
            //for (int i=0; i<net.panels.Count; i++)
            //{
            //    PanelService.remove (net.panels [i]);
            //}
            //proj.nets.Remove (net);
            int tempFalseNum = 0;
            for (int i = 0; i < net.panels.Count; i++)
            {
                if (!PanelService.remove(net.panels[i]))
                    tempFalseNum++;
            }
            if (tempFalseNum == 0)
                proj.nets.Remove(net);
            else
            {
                View.ViewUtils.showAlert("删除网络失败，请手动删除遗留面板，再尝试删除网络！");
                return;
            }
            /* end of [g2.s1] */
		}


		public static int newNetId()
		{
			for(int id=1; id<512; id++)
			{
				bool findFlag = false;
				for (int i = 0; i < proj.nets.Count; i++)
				{
					if (id == proj.nets[i].index)
					{
						findFlag = true;
						break;
					}
				}
				if (!findFlag) return id;
			}
			return -1;
		}

        //GC: reflect all the net instances in current project
        public static List<HR60_PanelSoft.Model.Net> findNets()
        {
            if (null == Proj.currentProj || null == Proj.currentProj.nets)
                return null;
            return Proj.currentProj.nets;
        }
	}
}
